<template>
    <div>
        <PageCard title="类别管理列表">
            <template #actions>
                <el-button class="ed-button ed_black-bottom ed-button36" v-if="$store.getters.type == 1" @click="addCate"><svg-icon icon-class="add-svg" v-has="'shopping:category:add'"/>添加类别</el-button>
                <!-- <el-dropdown class="floatRight" @command="clickVillageMenu"> -->
                    <!-- <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item v-for="item in typeOptions" :command="item" :key="item.type">{{item.desc}}</el-dropdown-item>
                    </el-dropdown-menu> -->
                <!-- </el-dropdown> -->
            </template>
            <ApiTable :api="load" ref="table" :params="queryForm" @cellMouseenterHover="cellMouseenterHover" @cellMouseLeaveHover="cellMouseLeaveHover">
                <el-table-column type="index" width="80" label="序号"></el-table-column>
                <el-table-column :show-overflow-tooltip="true" prop="categoryName" label="类别名称"/>
                <el-table-column :show-overflow-tooltip="true" prop="pic" label="显示图标">
                    <template slot-scope="scope">
                        <span v-if="scope.row.pic=='-'">-</span>
                        <el-image v-else style="width: 42px;height: 42px;" :src="scope.row.pic" fit="contain"></el-image>
                        
                    </template>
                </el-table-column>
                <!-- <el-table-column :show-overflow-tooltip="true" prop="id" label="ID"/> -->
                <el-table-column :show-overflow-tooltip="true" prop="createTime" label="创建时间"></el-table-column>
                <el-table-column :show-overflow-tooltip="true" prop="showStatus" label="显示/隐藏" v-if="$store.getters.type == 2 || $store.getters.type ==3">
                    <template slot-scope="scope">
                        {{scope.row.showStatus == 0 ? '隐藏' : '显示'}}
                        <el-switch v-model="scope.row.showStatus" :active-value="activeValue" :inactive-value="inactiveValue"
                            :value="scope.row.showStatus == '1' ? true : false"
                            @change="switchChange(scope.row)"
                            active-color="#EED096"
                            inactive-color="#909399">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column :show-overflow-tooltip="true" prop="" label="操作" width="400px">
                    <template slot-scope="scope">
                        <el-button class="ed-table-bottom ed_black_border" v-if="$store.getters.type == 1" @click="editCate(scope.row)" v-has="'shopping:category:edit'">编辑</el-button>
                        <el-button class="ed-table-bottom ed_blue_border" v-if="$store.getters.type == 1 && scope.row.level==1" @click="addType(scope.row)" v-has="'shopping:category:addChildren'">添加子类别</el-button>
                        <el-button class="ed-table-bottom ed_delete_border" v-if="$store.getters.type == 1" @click="del(scope.row)" v-has="'shopping:category:delete'" >删除</el-button>
                        <i v-if="$store.getters.type == 2 || $store.getters.type ==3" class="up-arrow el-icon-top colorBlue fontSize16  fontWeightBold cursorPointer" @click="up(scope.$index,scope.row)"></i>
                            <i v-if="$store.getters.type == 2 || $store.getters.type ==3" class="down-arrow el-icon-bottom colorBlue fontSize16 marginLeft10 fontWeightBold cursorPointer" @click="down(scope.$index,scope.row)"></i>
                        <!-- <i v-if="(scope.row.id == hoverId && scope.row.level == 1) && ($store.getters.type == 2 || $store.getters.type ==3)" class="el-icon-top colorBlue fontSize16 marginLeft20 fontWeightBold cursorPointer" @click="up(scope.row)"></i>
                        <i v-if="(scope.row.id == hoverId && scope.row.level == 1) && ($store.getters.type == 2 || $store.getters.type ==3)" class="el-icon-bottom colorBlue fontSize16 marginLeft10 fontWeightBold cursorPointer" @click="down(scope.row)" ></i> -->
                    </template>
                </el-table-column>
            </ApiTable>
        </PageCard>
        <EdDialog ref="dialogRef" v-if="showCategory" :title="isUpdate ? '编辑类别' : '添加类别'" width="490px" @close-dialog="closeDialog" @save-dialog="saveDialog">
            <el-form :model="form" ref="formRef" size="small" label-position='right' label-width="auto">
                <el-form-item label="类别名称"  style="margin-bottom: 24px;" :rules="$validate.validates({required:true,msg:'类别名称不能为空'})" prop="categoryName">
                    <el-input v-model="form.categoryName" style="width: 275px;" placeholder="请输入类别名称" maxlength="10" ></el-input>
                </el-form-item>
                <el-form-item label="上传图标" v-if="secondLevel" style="margin-bottom: 5px" prop="pic" :rules="$validate.validates({required:true,msg:'图标不能为空'})">
                    <el-upload
                            class="business-uploader-icon business-uploader-icon"
                            accept=".jpeg,.png,.jpg"
                            :action="action"
                            :headers="headers"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload">
                        <el-image v-if="form.pic" :src="form.pic" fit="contain"></el-image>
                        <div v-else>
                            <i class="el-icon-plus avatar-uploader-icon"></i>
                            <div style="font-size: 14px;color: rgba(0, 0, 0, 0.65); margin: 5px 0 0 0;line-height: 1">上传图片</div>
                        </div>
                    </el-upload>
                </el-form-item>
            </el-form>
        </EdDialog>
        <EdDialog ref="dialogTypeRef" v-if="showTypeCategory" title="添加子类别" width="490px" @close-dialog="closeTypeDialog" @save-dialog="saveTypeDialog">
            <el-form :model="Typeform" ref="formtypeRef" size="small" label-position='right' label-width="auto">
                <el-form-item label="子类别名称"  style="margin-bottom: 24px;" :rules="$validate.validates({required:true,msg:'类别名称不能为空'})" prop="categoryName">
                    <el-input v-model="Typeform.categoryName" style="width: 275px;" placeholder="请输入类别名称" maxlength="10" ></el-input>
                </el-form-item>
            </el-form>
        </EdDialog>
        <!-- <EdDialog ref="dialogRef" v-if="showCode" :title="title" width="490px" @close-dialog="closeDialog" @save-dialog="saveDialog">
            <el-form :model="form" ref="formRef" size="small" label-width="110px">
                <el-form-item label="类别名称：" v-if="title == '添加类别'" style="margin-bottom: 24px;" :rules="$validate.validates({required:true,msg:'类别名称不能为空'})" prop="categoryName">
                    <el-input v-model="form.categoryName" style="width: 275px;" placeholder="请输入类别名称" maxlength="10" ></el-input>
                </el-form-item>
                <el-form-item label="子类别名称：" v-if="title == '添加子类别'" :rules="$validate.validates({required:true,msg:'子类别名称不能为空'})" prop="categoryName">
                    <el-input v-model="form.categoryName" style="width: 275px;" placeholder="请输入子类别名称" maxlength="10" ></el-input>
                </el-form-item>
                 <el-form-item label="使用场景：">
                    <el-select v-model="form.scene" class="width-100" placeholder="请选择使用场景">
                        <el-option
                                v-for="item in sceneList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item> -->
                <!-- <el-form-item label="上传图标：" v-if="title == '添加类别'" style="margin-bottom: 5px" prop="pic" :rules="$validate.validates({required:true,msg:'营业执照不能为空'})">
                    <el-upload
                            class="business-uploader-icon business-uploader-icon"
                            accept=".jpeg,.png,.jpg"
                            :action="action"
                            :headers="headers"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload">
                        <el-image v-if="form.pic" :src="form.pic" fit="contain"></el-image>
                        <div v-else>
                            <i class="el-icon-plus avatar-uploader-icon"></i>
                            <div style="font-size: 14px;color: rgba(0, 0, 0, 0.65); margin: 5px 0 0 0;line-height: 1">上传图片</div>
                        </div>
                    </el-upload>
                </el-form-item>
            </el-form>
        </EdDialog> -->

        <ed-confirm-delete ref="confirmDeleteRef" @confirmDeleteTrue="confirmDeleteTrue()"></ed-confirm-delete>
    </div>
</template>

<script>
    import EdDialog from 'src/components/EdDialog.vue'
    import EdTable from "src/components/EdTable.vue";
    import EdConfirmDelete from "src/components/EdConfirmDelete.vue";
    import {getToken} from 'src/utils/auth'
    // import {addCategory ,moveUp ,moveDown ,delCategory ,getScene ,availableType ,getAllCategory} from "src/api/shoppingMall";
    import {cateList,moveUp ,moveDown ,delCategory ,getScene ,availableType,showStatusDown,showStatusuUp,addCategory,ShowCategory} from "./api";
    import Page from '../../components/Page.vue'
    import PageCard from 'src/views/components/PageCard.vue'
    import ApiTable from 'src/components/ApiTable.vue'
    import { defineComponent } from 'vue'
    export default defineComponent({
        name: "CategoryList",
        components:{EdTable,EdConfirmDelete,Page, PageCard, ApiTable,EdDialog},
        data(){
            return{
                queryForm:{
                    rowKey:"id",
                },
                secondLevel:true,
                showCode:false,
                isUpdate:false,
                form:{
                    categoryName:"",
                    pic:"",
                    scene:"",
                    type:""
                },
                // 编辑保存时要传的id
                id:'',
                Typeform:{
                    categoryName:''
                },
                action:"",
                headers:{
                    RdAuthorization: getToken()
                },
                hoverId:null,
                confirmRow:{},
                sceneList:[],
                addCommodityFont:"添加类别",
                typeOptions:[],
                showCategory:false,
                showTypeCategory:false,
                activeValue:1,
                inactiveValue:0,
            }
        },
        mounted(){
            this.action = this.$baseApi + "/file/upload";
            this.getScene();
            this.availableType();
            this.$nextTick(()=>{
                this.$refs.table.load(1)
            })
        },
        methods:{
            load:cateList,
            getScene(){
                getScene({}).then(response => {
                    if(response.code == 20000) {
                        this.sceneList = response.data;
                    }
                })
            },
            availableType(){
                availableType().then(response => {
                    if(response.code == 20000) {
                        this.typeOptions = response.data
                    }
                })
            },
            addCate(){
                // this.addCommodityFont = command.desc;
                // this.form.type = command.type;
                this.isUpdate=false
                this.showCategory = true
            },
            editCate(row){
                this.id = row.id
                this.showCategory = true
                this.isUpdate=true
                if(row.level==1){
                    this.secondLevel=true
                    ShowCategory({id:row.id}).then(response => {
                        if(response.success) {
                            this.form.categoryName = response.data.categoryName
                            this.form.pic = response.data.pic
                        }
                        this.$refs.table.load()
                    })
                } else {
                    this.secondLevel = false
                    ShowCategory({id:row.id}).then(response => {
                        if(response.success) {
                            this.form.categoryName = response.data.categoryName
                            // this.form.pic = response.data.pic
                        }
                        this.$refs.table.load()
                    })
                }
            },
            cellMouseenterHover(row) {
                this.hoverId = row.id
            },
            cellMouseLeaveHover(row) {
                this.hoverId = null
            },
            addType(row){
                this.title = "添加子类别";
                // this.form.parentId = row.id;
                // this.form.type = row.type;
                this.showTypeCategory = true
                this.Typeform.parentCode=row.code
            },
            del(row) {
                this.confirmRow = row;
                this.$refs.confirmDeleteRef.open("删除确认","确认删除此项数据？","warning")
            },
            confirmDeleteTrue(){
                delCategory({id: this.confirmRow.id}).then(response => {
                    if(response.code == 20000) {
                        this.$message.success({
                            message: '类别已删除成功！',
                            duration: 2000,
                            center:true
                        });
                        this.$refs.table.load(1)
                    }
                })
            },
            up(row){
                moveUp({id: row.id}).then(response => {
                    if(response.code == 20000) {
                        this.$message.success({
                            message: '类型上移成功',
                            duration: 2000,
                            center:true
                        });
                        this.$refs.table.load(1)
                    }
                })
            },
            down(row){
                moveDown({id: row.id}).then(response => {
                    if(response.code == 20000) {
                        this.$message.success({
                            message: '类型下移成功！',
                            duration: 2000,
                            center:true
                        });
                        this.$refs.table.load(1)
                    }
                })
            },
            closeDialog(){
                this.$refs.formRef.resetFields();
                this.showCategory = false;
                this.close()
            },
            closeTypeDialog(){
                this.$refs.formtypeRef.resetFields();
                this.showTypeCategory = false;
                this.close()
            },
            saveDialog(){
                this.save('formRef')
                this.$refs.dialogRef.loading=false
            },
            saveTypeDialog(){
                this.$refs['formtypeRef'].validate((valid)=>{
                    if(valid){
                       addCategory(this.Typeform).then(res=>{
                            if(res.success){
                                this.$message.success({
                                    message:'添加子类别成功',
                                    duration: 2000,
                                    center:true
                                })
                                this.showTypeCategory = false;
                                this.$refs.table.load(1)
                                this.Typeform.categoryName=''
                                // this.$refs.dialogTypeRef.resetFields()
                            }
                       }) 
                    }else {
                        this.$refs.dialogTypeRef.hideLoading()
                        // this.$refs.dialogTypeRef.resetFields()
                    }
                })
            },
            save(formName){
                this.$refs[formName].validate((valid) => {
                    if(!valid){
                        this.$refs.dialogRef.loading=false
                        return
                    }
                    // 编辑保存的接口
                    this.form.id = this.id
                    if(this.isUpdate){
                        addCategory(this.form).then(res=>{
                            if(res.success){
                                this.$message.success({
                                    message: '编辑成功！',
                                    duration: 2000,
                                    center:true
                                });
                                this.$refs.dialogRef.close();
                                this.$refs.table.load()
                            }
                            this.$refs.dialogRef.loading()
                        }).catch(()=>{
                            this.$refs.dialogRef.hideLoading()
                        })
                    }else {
                        this.form.id= null
                        addCategory(this.form).then(res=>{
                            if(res.success){
                                this.$message.success({
                                    message: '添加类别成功！',
                                    duration: 2000,
                                    center:true
                                });
                                this.$refs.dialogRef.close();
                                this.$refs.table.load()
                            }
                        }).catch(()=>{
                            this.$refs.dialogRef.hideLoading()
                        })
                    }
                })
            },
            handleAvatarSuccess(file){
                this.form.pic = file.data;
            },
            beforeAvatarUpload(file){
                const fileType = file.name.split('.');
                const fileDate = fileType.slice(-1);
                if (['jpeg', 'jpg', 'png'].indexOf(fileDate[0]) < 0) {
                    this.$message.error('仅支持格式：.jpeg、.jpg、.png!');
                    return false
                }
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                    this.$message.error('上传文件大小不能超过 2MB!');
                }
                return isLt2M;
            },
            close(){
                this.form={
                    categoryName:"",
                    pic:"",
                    scene:"",
                    type:""
                }
            },
            switchChange(row){
                let urlFn = null;
               if(row.showStatus === 1){
                   urlFn = showStatusuUp;
               }else {
                   urlFn = showStatusDown;
               }
                urlFn({id:row.id}).then(response => {
                    if(response.code == 20000) {
                        this.$message.success({
                            message: row.showStatus === 1 ?  '已切换为显示' : "已切换为隐藏",
                            duration: 2000,
                            center:true
                        });
                    }
                })
            },
        }
    })
</script>

<style scoped>
    .business-uploader-icon .el-upload{
        width: 104px;
        height: 104px;
        background: rgba(0, 0, 0, 0.04);
        border: 1px dashed rgba(0, 0, 0, 0.14901960784313725);
        border-radius: 2px;
        display: flex;
        -webkit-display: flex;
        justify-content: center;
        align-items: center;
        overflow: hidden;
    }

    .business-uploader-icon .el-upload .el-icon-plus{
        font-size: 24px;
        color: rgba(0, 0, 0, 0.45);
    }

    .business-uploader-icon .el-dialog__footer{
        border-top:1px solid rgba(0, 0, 0, 0.06);
    }

    :deep(.up-arrow) {
    visibility: hidden; 
    
    }
    :deep(.down-arrow) {
        visibility: hidden; 
        
    }
    :deep(.table-row:hover .up-arrow) {
        visibility: visible;
        
    }
    :deep(.table-row:hover .down-arrow) {
        visibility: visible; 
        
    }

    :deep(.table-row:first-of-type .up-arrow) {
        opacity: 0.3;
        pointer-events: none;
    }
    :deep(.table-row:last-of-type .down-arrow) {
        opacity: 0.3;
        pointer-events: none;
    }
</style>